import { getPosition, setPosition, saveUserInfo, getUserInfo, logout, setOrders, getOrders } from '../etc/datas'

import { SET_POSITION, SET_USERINFO, SET_ORDERS, ADD_CART, REDUCE_CART, } from './mutations';


export default {

    setPositionId(store, positionId) { // 设置定位
        let [latitude, longitude] = positionId.split(',')
        let position = { latitude, longitude }
        setPosition(() => { // 把定位存到本地
            store.commit(SET_POSITION, position)
        }, position)
    },

    initPosition(store, vm) { // 初始化定位，假如失败则回首页
        if (!store.position) {
            getPosition(data => {
                if (data) {
                    store.commit(SET_POSITION, data)
                } else {
                    vm.$router.replace('/')
                }
            })
        }
    },


    // 保存登录信息
    saveUserInfo(store, userInfo) {
        saveUserInfo(data => {
            store.commit(SET_USERINFO, data)
        }, userInfo)
    },

    // 获取用户信息
    initUserInfo(store) {
        if (!store.userInfo) {
            getUserInfo(data => {
                if (data) {
                    store.commit(SET_USERINFO, data)
                }
            })
        }
    },

    logout(store, vm) {
        logout(() => {
            store.commit(SET_USERINFO, null)
            vm.$router.replace('/')
        })
    },



    // 购物车
    initOrders(store) {
        if (!store.orders) {
            getOrders(data => {
                store.commit(SET_ORDERS, data)
            })
        }
    },
    cartAdd(store, data) {
        store.commit(ADD_CART, data)
        setOrders(null, store.state.orders)
    },
    cartReduce(store, data) {
        store.commit(REDUCE_CART, data)
        setOrders(null, store.state.orders)
    },
    clearCart(store) {
        store.commit(SET_ORDERS, {})
        setOrders(null, store.state.orders)
    }

}
